<script setup>
import { vDraggable } from 'vue-draggable-plus'
import { nanoid } from 'nanoid'
import { cloneDeep, throttle } from 'lodash-es'
import { provideDragKey } from '../../hooks/use-provide-key'
import RenderItem from './render-item.vue'
import RenderInput from './widgets/input.vue'
import RenderInputNumber from './widgets/input-number.vue'
import RenderText from './widgets/text.vue'
import RenderTitle from './widgets/title.vue'
import RenderCheckbox from './widgets/checkbox.vue'
import RenderRadio from './widgets/radio.vue'
import RenderSwitch from './widgets/switch.vue'
import RenderSelect from './widgets/select.vue'
import RenderDatePicker from './widgets/date-picker.vue'
import RenderTimePicker from './widgets/time-picker.vue'

import { useTemplateStore } from '@/stores'

const schema = defineModel('schema')
const currentItem = defineModel('currentItem')
const currentRow = defineModel('currentRow')

const templateStore = useTemplateStore()
watch(
  () => templateStore.currentTemplate,
  val => {
    schema.value.id = val?.value?.id ?? ''
    schema.value.name = val?.value?.name ?? ''
    schema.value.formProps = val?.value?.formProps ?? {}
    schema.value.data = val?.value?.data ?? {}
    const len = schema.value?.fieldList?.length ?? 0
    schema.value.fieldList?.splice(0, len)
    schema.value.fieldList?.push(...(val?.value?.fieldList ?? []))
  },
)

const { group } = inject(provideDragKey)

// 当前选中的列、行
const handleSelectItem = item => {
  currentItem.value = item ?? {}
}
const handleSelectRow = item => {
  currentRow.value = item
}

// 列格操作
const removeField = (index, parentList) => {
  parentList.splice(index, 1)
}
const copyField = (item, index, parentList) => {
  parentList.splice(index + 1, 0, {
    ...cloneDeep(item),
    id: `${item.type}-${nanoid(4)}`,
    field: `${item.type}-${nanoid(4)}`,
  })
}

// hover 显示行操作
const hoverIndex = ref(null)
const handleMouseenter = throttle(index => {
  hoverIndex.value = index
}, 500)
const handleMouseleave = throttle(index => {
  hoverIndex.value = null
}, 500)
const handleAddRow = (rowItem, index) => {
  schema.value.fieldList.splice(index + 1, 0, {
    ...cloneDeep(rowItem),
    id: `${rowItem.type}-${nanoid(4)}`,
    children: [],
  })
}
const handleRemoveRow = index => {
  schema.value.fieldList.splice(index, 1)
}

// 表格里显示的组件
const componentMap = {
  input: RenderInput,
  inputNumber: RenderInputNumber,
  text: RenderText,
  title: RenderTitle,
  checkbox: RenderCheckbox,
  radio: RenderRadio,
  switch: RenderSwitch,
  select: RenderSelect,
  datePicker: RenderDatePicker,
  timePicker: RenderTimePicker,
}
</script>

<template>
  <div class="borderClass h-full w-full bg-gray-500/5 overflow-auto">
    <div class="p-5 h-full w-full">
      <el-form
        :model="schema.data"
        v-bind="schema.formProps"
        class="h-full"
        v-draggable="[schema.fieldList, { animation: 150, group: group.name }]"
      >
        <template
          v-for="(item, index) of schema.fieldList"
          :key="item.id"
        >
          <template v-if="item.type === 'row'">
            <el-row
              v-bind="item.props"
              class="activeClass position-relative min-h-40px hover:bg-gray-500/10"
              v-draggable="[
                item.children,
                { animation: 150, group: group.name },
              ]"
              @mouseenter="handleMouseenter(index)"
              @mouseleave="handleMouseleave(index)"
              @click="handleSelectRow(item)"
            >
              <template
                v-for="(child, childIndex) of item.children"
                :key="child.id"
              >
                <el-col
                  v-bind="child.colProps"
                  class="p-2 position-relative cursor-move rounded hover:bg-gray-500/10"
                  :class="currentItem === child ? 'activeClass' : ''"
                  @click="handleSelectItem(child)"
                >
                  <el-form-item
                    class="mb-0!"
                    v-bind="child.formItemProps"
                  >
                    <component
                      :is="componentMap[child.type]"
                      :field="child"
                    />
                  </el-form-item>
                  <div
                    v-show="child === currentItem"
                    class="position-absolute right-0 bottom-0"
                  >
                    <el-button-group size="small">
                      <el-button
                        icon="CopyDocument"
                        type="primary"
                        plain
                        @click="copyField(child, childIndex, item.children)"
                      />
                      <el-button
                        icon="Delete"
                        type="danger"
                        plain
                        @click="removeField(childIndex, item.children)"
                      />
                    </el-button-group>
                  </div>
                </el-col>
              </template>
              <div
                v-show="hoverIndex === index"
                class="flex flex-col position-absolute left-[-25px] bottom-[-10px]"
              >
                <el-tooltip
                  placement="left"
                  content="删除行"
                >
                  <el-button
                    @click="handleRemoveRow(index)"
                    icon="Minus"
                    size="small"
                    text
                    type="danger"
                    class="ml-0! h-20px!"
                  />
                </el-tooltip>
                <el-tooltip
                  placement="left"
                  content="新增行"
                >
                  <el-button
                    @click="handleAddRow(item, index)"
                    icon="Plus"
                    size="small"
                    text
                    type="primary"
                    class="ml-0! h-20px!"
                  />
                </el-tooltip>
              </div>
            </el-row>
          </template>
          <template v-else>
            <div
              class="position-relative cursor-move rounded hover:bg-gray-500/10"
            >
              <RenderItem
                :field="item"
                @click="handleSelectItem(item)"
                :class="currentItem === item ? 'activeClass' : ''"
              />
              <div
                v-show="item === currentItem"
                class="position-absolute right-0 bottom-0"
              >
                <el-button-group size="small">
                  <el-button
                    icon="CopyDocument"
                    type="primary"
                    plain
                    @click="copyField(item, index, schema.fieldList)"
                  />
                  <el-button
                    icon="Delete"
                    type="danger"
                    plain
                    @click="removeField(index, schema.fieldList)"
                  />
                </el-button-group>
              </div>
            </div>
          </template>
        </template>
      </el-form>
    </div>
  </div>
</template>
